package cn.lanqiao.cglib;

import cn.lanqiao.cglib.impl.Target;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class TargetProxyTest {
    public static void main(String[] args) {
        //代理的目标对象
        final Target target = new Target();
        //增强类
        final Advice advice = new Advice();
        Enhancer enhancer = new Enhancer();

        //设置代理对象的父类，父类就是目标对象自己的class
        enhancer.setSuperclass(Target.class);
        enhancer.setCallback(new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                advice.before();
                //执行目标方法
                Object invoke = method.invoke(target,args);
                advice.after();
                return invoke;
            }
        });
        // 生成代理对象
        Target proxy = (Target) enhancer.create();
        proxy.save();
    }
}
